<template>
  <!-- 产量分析 -->
  <BaseMainSlot @richheight="setheigt">
    <template v-slot:content>
      <div class="analysis-list">
        <div class="search-list">
          
          <div class="analy-list-itemone">
            <div class="itemone-one">
              <div class="search-line">
                选择年份：
                <el-date-picker v-model="searchone.year" type="year" value-format="yyyy" format="yyyy" clearable
                  @change="getfacilitylisttwo(),searchone.fishPondId=''" />
              </div>
              <div class="search-line">
                选择鱼塘：
                <el-select filterable clearable v-model="searchone.fishPondId" filterable clearable @change="getfacilitylisttwo" :disabled='!searchone.year'>
                  <el-option v-for="facilityitem in searchone.facilityList" :key="facilityitem.fishPondId"
                    :label="facilityitem.pondName" :value="facilityitem.fishPondId"/>
                </el-select>
              </div>
              <div class="search-line">
                选择批次：
                <el-select filterable clearable v-model="searchone.productionBatchId" filterable clearable :disabled='!searchone.fishPondId'>
                  <el-option v-for="batchitem in searchone.batchList" :key="batchitem.productionBatchId"
                    :label="batchitem.mnecode" :value="batchitem.productionBatchId" />
                </el-select>
              </div>
            </div>
            <div class="itemone-two">
              <div class="linetwo-one" @click="addline()" v-show="forlist.length==0">
                <i class="el-icon-plus"></i>
              </div>
              <div class="search-btn search-btns" @click.stop="toanalysisdata()">
                <i class="el-icon-circle-check"></i>
                <p>查询</p>
              </div>
            </div>
          </div>

          <div v-for="(item, index) in forlist" :key="index" class="analy-list-itemone">
            <div class="itemone-one">
              <div class="search-line">
                选择年份：
                <el-date-picker v-model="searchtwolist[index].year" type="year" value-format="yyyy" format="yyyy" clearable 
                  @change="getbatchlist($event, searchtwolist[index].year, index),searchtwolist[index].fishPondId=''"/>
              </div>
              <div class="search-line">
                选择鱼塘：
                <el-select filterable clearable v-model="searchtwolist[index].fishPondId" clearable :disabled='!searchtwolist[index].year'
                  @change="getbatchlist($event, searchtwolist[index].year, index)">
                  <el-option v-for="facilityitem in searchtwolist[index].facilityList" :key="facilityitem.fishPondId"
                    :label="facilityitem.pondName" :value="facilityitem.fishPondId" />
                </el-select>
              </div>
              <div class="search-line">
                选择批次：
                <el-select filterable clearable v-model="searchtwolist[index].productionBatchId" clearable :disabled='!searchtwolist[index].fishPondId'>
                  <el-option v-for="batchitem in searchtwolist[index].batchList" :key="batchitem.productionBatchId"
                    :label="batchitem.mnecode" :value="batchitem.productionBatchId" />
                </el-select>
              </div>
            </div>
            <!-- 占个位置对齐 -->
            <div class="itemone-two">
              <!-- 减少按钮 -->
              <div class="itemone-two">
                <div class="linetwo-one" @click="delline('addDelline',index)">
                  <i class="el-icon-minus"></i>
                </div>
                <div class="linetwo-one" @click="addline()" v-show="forlist.length==index+1">
                <i class="el-icon-plus"></i>
              </div>
              </div>
            </div>
          </div>
        </div>
        <!-- <CategoryBar :categoryList="categoryList" @categoryBar="categorySearch" /> -->
        <div ref="zklchart" class="zchart">
          <zhchart v-if="testchartlist.xAxisdata.length > 0 && noselecttypestau === 0" ref="testyuy"
            :cdata="testchartlist" :nowwidth="'100%'" :nowheight="'100%'" />
          <zhchart v-else-if="testchartlistx.xAxisdata.length > 0 && noselecttypestau === 1" ref="testyuy"
            :cdata="testchartlistx" :nowwidth="'100%'" :nowheight="'100%'" />
          <div class="zcharts" v-else>
            请先选择 年份 -> 鱼塘 -> 批次 点击查询 预计效果：
            <zhchart ref="testyuy" :cdata="testchartlists" :nowwidth="'100%'" :nowheight="'100%'" />
          </div>
        </div>
      </div>
    </template>
  </BaseMainSlot>
</template>
<script>
import CategoryBar from "@/components/CategoryBar/index.vue";
// import nowpagereq from "@/api/digital-production/production-statistics/yield-analysis";
import fishPondApi from "@/api/basic-info-manage/fishPond";
import outputRecordApi from "@/api/output-manage/output-record";

import BaseMainSlot from "@/components/BaseMainSlot/baseone.vue";
import { mymixin } from "@/utils/mixin";
import zhchart from "@/components/Echarts/components/linechart/chart.vue";
import * as echarts from "echarts";

// import { getToken } from '@/utils/auth';
export default {
  name: "YieldAnalysis",
  components: { BaseMainSlot, CategoryBar, zhchart },
  mixins: [mymixin],
  data () {
    return {
      // 当前选择状态
      noselecttypestau: 0,
      // 对比搜索项1
      searchone: {
        year: "",             // 年份
        facilityList: [],     // 鱼塘下拉
        fishPondId: "",       // 鱼塘ID
        batchList: [],        // 批次下拉
        productionBatchId: "" // 批次id
      },
      // 对比搜索2
      searchtwolist: [
        // {
        //   year: "",
        //   batchList: [],
        //   facilityList: [],
        //   fishPondId: "",
        //   productionBatchId: ""
        // }
      ],
      // 循环数组,每次点击加号里面加个1
      forlist: [],
      categoryList: [
        { name: "总产量", id: 0 },
        { name: "亩产量", id: 1 }
      ],
      // ----
      newwidth: "100%",
      newheight: "100%",
      testchartlist: {
        xAxisdata: [],
        xData: ["产量（千克）"],
        seriesData: [
          {
            name: "产量（千克）",
            type: "line",
            data: [],
            barMaxWidth: 60,
            itemStyle: {
              normal: {
                borderRadius: [10, 10, 0, 0],
                // barBorderRadius: 5,
                // barBorderRadius: [10, 10, 0, 0],
                color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                  { offset: 0, color: "#04FA99" },
                  { offset: 1, color: "#3EACE5" }
                ])
              }
            }
          }
        ]
      },
      testchartlists: {
        xAxisdata: ["产量示例"],
        xData: ["产量示例"],
        seriesData: [
          {
            name: "产量示例（千克）",
            type: "bar",
            data: [300],
            barMaxWidth: 60,
            itemStyle: {
              normal: {
                borderRadius: [10, 10, 0, 0],
                // barBorderRadius: 5,
                // barBorderRadius: [10, 10, 0, 0],
                color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                  { offset: 0, color: "#04FA99" },
                  { offset: 1, color: "#3EACE5" }
                ])
              }
            }
          }
        ]
      },
      testchartlistx: {
        xAxisdata: ["产量示例"],
        xData: ["产量示例"],
        seriesData: [
          {
            name: "产量示例（千克）",
            type: "bar",
            data: [300],
            barMaxWidth: 60,
            itemStyle: {
              normal: {
                borderRadius: [10, 10, 0, 0],
                // barBorderRadius: 5,
                // barBorderRadius: [10, 10, 0, 0],
                color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                  { offset: 0, color: "#04FA99" },
                  { offset: 1, color: "#3EACE5" }
                ])
              }
            }
          }
        ]
      }
    };
  },
  watch: {
    noselecttypestau (newvalue) {
      this.toanalysisdata();
    }
  },
  mounted () {
    this.getheight();
    this.getbatchlisttwo("2021");
    // this.toanalysisdata()
    // this.getlastmessageone();
  },
  methods: {
    // 当前选择的时0总产量-1亩均产量
    categorySearch (i) {
      this.noselecttypestau = i.id;
    },
    // 获取批次
    getfacilitylisttwo () {
      this.searchone.productionBatchId=''
      !this.searchone.year && this.$message.info('请选择你年份！')
      this.searchone.year && outputRecordApi.queryByYear({
        fishPondId: this.searchone.fishPondId,
        year: this.searchone.year
      })
        .then(res => {
          this.searchone.batchList = res.data;
          !this.searchone.batchList.length && this.$message.info('您选择的年份或鱼塘无批次信息！')
        });
    },
    // 批次选择
    async getbatchlisttwo (e) {
      let dateparams = {};
      // nowpagereq.getbatchlist(dateparams).then(res => {
      //   this.searchone.batchList = res.data;
      // });

      // 获取鱼塘
      const { data: resp } = await fishPondApi.queryByCondition({});
      if (resp !== undefined) {
        this.searchone.facilityList = resp;
      } else this.searchone.facilityList = [];
    },
    // 批次选择
    getbatchlist (e, year, nowselectindex) {
      if (!this.searchtwolist[nowselectindex].year) {
        this.$message.info('请选择你年份！') 
        return
      }
      this.searchtwolist[nowselectindex].productionBatchId=''
      const zhdt = new Date(e);
      const y = zhdt.getFullYear();
      let dateparams = {
        fishPondId: e,
        year: year
      }; 
      outputRecordApi.queryByYear(dateparams).then(res => {
        this.searchtwolist[nowselectindex].batchList = res.data;
        !this.searchtwolist[nowselectindex].batchList.length && this.$message.info('您选择的年份或鱼塘无批次信息！')
      });
    },
    // 添加一条对比数据
    addline () {
      this.searchtwolist.push({
        year: this.searchone.year,
        batchList: [],
        facilityList: this.searchone.facilityList,
        fishPondId: "",
        productionBatchId: ""
      });
      this.forlist.push(1);
    },
    // 删除一条对比数据
    delline (delline,index) {
      if (delline=='addDelline') {
        this.searchtwolist.splice(index,1);
        this.forlist.splice(index,1)
      }else{
        this.searchtwolist.pop();
        this.forlist.pop();
      }
    },
    // 点击数据对比方法
    toanalysisdata () {

      let paramsListone = [];
      paramsListone.push(this.searchone.productionBatchId);
      this.searchtwolist.forEach(item => {
        paramsListone.push(item.productionBatchId);
      });
      let a=paramsListone.filter((item)=>{
        return item!=''
      })
      // 获取产量
      outputRecordApi
        .analysisCondition({ batchIdList: a })
        // .analysisCondition({ batchIdList: paramsListone })
        .then(res => {
          if (res.errCode !== undefined) {
            this.$message.warning("暂无数据");
          } else {
            this.chancedata(res.data);
          }
        });
    },
    // 后端数据处理方法
    chancedata (list) {
      let nowlist = JSON.parse(JSON.stringify(list));
      // if (!nowlist[0]["partYieldList"]) {
      //   this.$message.warning("数据错误，请检查");
      //   return;
      // }
      console.log(list);
      // let newlist = [];
      // nowlist.forEach((item, index) => {
      //   let objitem = {
      //     name: "产量（千克）",
      //     type: "bar",
      //     barMaxWidth: 60,
      //     itemStyle: {
      //       normal: {
      //         borderRadius: [10, 10, 0, 0],
      //         color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
      //           { offset: 0, color: "#04FA99" },
      //           { offset: 1, color: "#3EACE5" }
      //         ])
      //       }
      //     },
      //     data: []
      //   };
      //   list.forEach((lhitem, lhindex) => {
      //     objitem.data.push(lhitem.totalWeight);
      //   });
      //   newlist.push(objitem);
      // });
      let newlist = [
        {
          name: "产量（千克）",
          type: "bar",
          barMaxWidth: 60,
          itemStyle: {
            normal: {
              borderRadius: [10, 10, 0, 0],
              color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                { offset: 0, color: "#04FA99" },
                { offset: 1, color: "#3EACE5" }
              ])
            }
          },
          data: nowlist.map(item => {
            return item.totalWeight;
          })
        }
      ];
      let nowlists = [
        {
          name: "产量（千克）",
          type: "bar",
          barMaxWidth: 60,
          itemStyle: {
            normal: {
              borderRadius: [10, 10, 0, 0],
              color: new echarts.graphic.LinearGradient(1, 0, 0, 1, [
                { offset: 0, color: "#04FA99" },
                { offset: 1, color: "#3EACE5" }
              ])
            }
          },
          data: nowlist.map(item => {
            return item.avgWeight;
          })
        }
      ];
      // 获取x轴数据
      let xAxisdata = [];
      // nowlist.forEach(xitem => {
      //   xAxisdata.push(xitem.mnecode);
      // });
      xAxisdata = nowlist.map(item => {
        return item.mnecode;
      });
      console.log(xAxisdata);

      this.testchartlist.xAxisdata = xAxisdata;
      this.testchartlist.seriesData = newlist;
      this.testchartlistx.xAxisdata = xAxisdata;
      this.testchartlistx.seriesData = nowlists;
    },
    save () {
      console.log("save");
    },
    getheight () {
      const klll = this.$refs.zklchart;
      let heightone = klll.scrollHeight;
      this.newheight = heightone + "px";
      this.$refs.testyuy.resetsty();
    },
    setheigt (e) {
      this.getheight();
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep {
  .zhcontent {
    overflow: hidden !important;
  }
}

.search-list {
  width: 100%;
  height: 100px;
  overflow: auto;
}

.analysis-list {
  width: 100%;
  height: 100%;
  // border: rgb(55, 211, 55) solid 1px;
  font-size: 20px;

  // overflow: auto;
  .analy-list-itemone {
    width: 100%;
    display: flex;
    height: 50px;
    flex-direction: row;

    // justify-content: space-between;
    .itemone-one {
      width: 80%;
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      margin: 5px;

      .search-line {
        display: flex;
        white-space: nowrap;
        height: 50px;
        line-height: 50px;
      }
    }

    .itemone-two {
      width: 20%;
      display: flex;
      flex-direction: row;
      align-items: center;

      .linetwo-one {
        cursor: pointer;
        width: 30px;
        height: 30px;
        border: #3ed2d2 1px solid;
        text-align: center;
        line-height: 30px;
        color: #3ed2d2;
        margin-left: 10px;
        margin-right: 2px;
      }

      .linetwo-two {
        cursor: pointer;
        width: 100px;
        height: 50px;
        margin-left: 10px;
        // background-image: url("~@/assets/analy.png");
        background-position: center;
        background-repeat: no-repeat;
      }
    }
  }
}

.zchart {
  // background-color: turquoise;
  width: 100%;
  margin-top: 10px;
  height: calc(100% - 200px);

  .zcharts {
    width: 100%;
    height: 100%;
  }

  // background-color: turquoise;
}

::v-deep .el-input--medium .el-input__icon {
  height: 46px;
  line-height: 36px;
}
</style>
